// 方块形状定义
const SHAPES = {
  I: {
    matrix: [
      [0, 0, 0, 0],
      [1, 1, 1, 1],
      [0, 0, 0, 0],
      [0, 0, 0, 0]
    ],
    type: 1
  },
  O: {
    matrix: [
      [1, 1],
      [1, 1]
    ],
    type: 2
  },
  T: {
    matrix: [
      [0, 1, 0],
      [1, 1, 1],
      [0, 0, 0]
    ],
    type: 3
  },
  L: {
    matrix: [
      [0, 0, 1],
      [1, 1, 1],
      [0, 0, 0]
    ],
    type: 4
  },
  J: {
    matrix: [
      [1, 0, 0],
      [1, 1, 1],
      [0, 0, 0]
    ],
    type: 5
  },
  S: {
    matrix: [
      [0, 1, 1],
      [1, 1, 0],
      [0, 0, 0]
    ],
    type: 6
  },
  Z: {
    matrix: [
      [1, 1, 0],
      [0, 1, 1],
      [0, 0, 0]
    ],
    type: 7
  }
}

// 创建游戏初始状态
export const createGameState = () => {
  return {
    gameMatrix: Array(20).fill().map(() => Array(10).fill(0)),
    currentPiece: null,
    currentX: 0,
    currentY: 0,
    nextPiece: getRandomPiece(),
    nextPieceMatrix: Array(4).fill().map(() => Array(4).fill(0)),
    score: 0,
    level: 1,
    lines: 0,
    isPlaying: false,
    isPaused: false
  }
}

// 获取随机方块
const getRandomPiece = () => {
  const pieces = Object.values(SHAPES)
  return pieces[Math.floor(Math.random() * pieces.length)]
}

// 检查碰撞
const checkCollision = (matrix, piece, x, y) => {
  const pieceMatrix = piece.matrix
  
  for (let row = 0; row < pieceMatrix.length; row++) {
    for (let col = 0; col < pieceMatrix[row].length; col++) {
      if (pieceMatrix[row][col]) {
        const newX = Math.floor(x + col)
        const newY = Math.floor(y + row)
        
        if (newX < 0 || newX >= matrix[0].length || 
            newY >= matrix.length ||
            (newY >= 0 && matrix[newY][newX])) {
          return true
        }
      }
    }
  }
  return false
}

// 旋转矩阵
const rotateMatrix = (matrix) => {
  // 获取矩阵尺寸
  const rows = matrix.length
  const cols = matrix[0].length
  
  // 创建新矩阵
  const rotated = Array(cols).fill().map(() => Array(rows).fill(0))
  
  // 90度顺时针旋转
  for (let row = 0; row < rows; row++) {
    for (let col = 0; col < cols; col++) {
      rotated[col][rows - 1 - row] = matrix[row][col]
    }
  }
  
  return rotated
}

// 合并方块到游戏面板
const mergePiece = (gameMatrix, piece, x, y) => {
  const pieceMatrix = piece.matrix
  
  for (let row = 0; row < pieceMatrix.length; row++) {
    for (let col = 0; col < pieceMatrix[row].length; col++) {
      if (pieceMatrix[row][col]) {
        const newY = y + row
        if (newY >= 0) {
          gameMatrix[newY][x + col] = piece.type
        }
      }
    }
  }
}

// 清除完整的行
const clearLines = (gameMatrix) => {
  let linesCleared = 0
  
  for (let row = gameMatrix.length - 1; row >= 0; row--) {
    if (gameMatrix[row].every(cell => cell > 0)) {
      gameMatrix.splice(row, 1)
      gameMatrix.unshift(Array(10).fill(0))
      linesCleared++
      row++
    }
  }
  
  return linesCleared
}

// 初始化游戏
export const initGame = (gameState) => {
  const state = gameState.value
  
  const spawnPiece = () => {
    state.currentPiece = state.nextPiece
    state.currentX = Math.floor((state.gameMatrix[0].length - state.currentPiece.matrix[0].length) / 2)
    state.currentY = 0
    state.nextPiece = getRandomPiece()
    
    // 更新预览区域
    state.nextPieceMatrix = Array(4).fill().map(() => Array(4).fill(0))
    const pieceMatrix = state.nextPiece.matrix
    const offsetY = Math.floor((4 - pieceMatrix.length) / 2)
    const offsetX = Math.floor((4 - pieceMatrix[0].length) / 2)
    
    for (let row = 0; row < pieceMatrix.length; row++) {
      for (let col = 0; col < pieceMatrix[row].length; col++) {
        if (pieceMatrix[row][col]) {
          state.nextPieceMatrix[offsetY + row][offsetX + col] = 1
        }
      }
    }
    
    // 检查游戏是否结束
    if (checkCollision(state.gameMatrix, state.currentPiece, state.currentX, state.currentY)) {
      endGame()
      return true
    }
    return false
  }

  // 添加游戏结束处理函数
  const endGame = () => {
    state.isPlaying = false
    state.isPaused = false
    alert(`游戏结束！\n最终得分：${state.score}\n消除行数：${state.lines}\n达到等级：${state.level}`)
  }
  
  return {
    start() {
      if (state.isPlaying) return
      Object.assign(state, createGameState())
      state.isPlaying = true
      state.isPaused = false
      spawnPiece()
    },
    
    update() {
      if (!state.isPlaying || state.isPaused) return
      
      if (checkCollision(state.gameMatrix, state.currentPiece, state.currentX, state.currentY + 1)) {
        // 如果碰撞，先合并方块
        mergePiece(state.gameMatrix, state.currentPiece, state.currentX, state.currentY)
        
        // 检查并清除完整的行
        const linesCleared = clearLines(state.gameMatrix)
        if (linesCleared > 0) {
          state.lines += linesCleared
          state.score += linesCleared * 100 * state.level
          state.level = Math.floor(state.lines / 10) + 1
        }
        
        // 生成新方块，如果返回true表示游戏结束
        if (spawnPiece()) {
          endGame()
          return
        }
      } else {
        state.currentY++
      }
    },
    
    moveLeft() {
      if (!state.isPlaying || state.isPaused) return
      const newX = Math.floor(state.currentX - 1)
      if (!checkCollision(state.gameMatrix, state.currentPiece, newX, state.currentY)) {
        state.currentX = newX
      }
    },
    
    moveRight() {
      if (!state.isPlaying || state.isPaused) return
      const newX = Math.floor(state.currentX + 1)
      if (!checkCollision(state.gameMatrix, state.currentPiece, newX, state.currentY)) {
        state.currentX = newX
      }
    },
    
    moveDown() {
      if (!state.isPlaying || state.isPaused) return
      if (!checkCollision(state.gameMatrix, state.currentPiece, state.currentX, state.currentY + 1)) {
        state.currentY++
      }
    },
    
    rotate() {
      if (!state.isPlaying || state.isPaused) return
      
      const rotated = {
        ...state.currentPiece,
        matrix: rotateMatrix(state.currentPiece.matrix)
      }
      
      // 尝试基本旋转
      if (!checkCollision(state.gameMatrix, rotated, state.currentX, state.currentY)) {
        state.currentPiece = rotated
        return
      }
      
      // 如果基本旋转失败，尝试左右移动后旋转（墙踢）
      const kicks = [-1, 1, -2, 2] // 尝试的偏移量
      for (const kick of kicks) {
        if (!checkCollision(state.gameMatrix, rotated, state.currentX + kick, state.currentY)) {
          state.currentPiece = rotated
          state.currentX += kick
          return
        }
      }
    },
    
    dropDown() {
      if (!state.isPlaying || state.isPaused) return
      while (!checkCollision(state.gameMatrix, state.currentPiece, state.currentX, state.currentY + 1)) {
        state.currentY++
      }
      this.update()
    },
    
    togglePause() {
      if (!state.isPlaying) return
      state.isPaused = !state.isPaused
    }
  }
} 